<!-- 我的考试-考试配置-组件 -->
<script setup lang='ts'>
  import { ref, reactive, computed, onMounted, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import type { ElForm } from 'element-plus';
  import SelectPaper from './selectPaper/index.vue';
  import PaperPreview from '@/components/paper-preview/index.vue';
  import { papaerDataType } from '@/common/types/paper-preview';
  import { useCurrentInstance } from '@/common/utils/methods';
  import { ResponseType } from '@/common/types/response'
  import { getPrevRouteInfo } from '@/common/utils/utils'
  import { useStore } from 'vuex';
  import { key } from '@/store/index'

  const { $message, $axios, branchId, brandId } = useCurrentInstance();
  const route = useRoute();
  const router = useRouter();
  const store = useStore(key);

  interface configType {
    timeLimit: string | number
    testAgain: number
    isForce: number
    cycleType: number
    startTm: string
    endTm: string
    cycleTimes: string | number
    
  }
  const props = defineProps<{ 
    config: configType
  }>()

  const emit = defineEmits<{
    (e: 'update:config', data: configType): void
    (e: 'verify'): void
  }>()

  const unit = computed(() => ['次', '周', '月'][ruleForm.cycleType - 2]);
  const needExamType = computed(() => !route.query.planId);
  const data = reactive({
    paperList: [],
    typesList: [],
    selectPaperRow: {} as papaerDataType,
    previewDialog: false,
    selectDialog: false,
    cycleType: [
      { key: 1, val: '仅一次' },
      { key: 2, val: '每日一次' },
      { key: 3, val: '每周一次' },
      { key: 4, val: '每月一次' }
    ]
  })

  const ruleForm = reactive({
    timeLimit: '',
    testAgain: 1,
    examType: '',
    isForce: 0,
    cycleType: 1,
    startTm: '',
    endTm: '',
    cycleTimes: '',
    paperId: '',
  })
  
  const rules = reactive({
    title: [
      { required: true, message: '请输入试卷', trigger: 'blur' }
    ],
    startTm: [
      { required: true, message: '请选择开始时间', trigger: 'blur' }
    ],
    endTm: [
      { required: true, message: '请选择结束时间', trigger: 'blur' }
    ],
    cycleTimes: [
      { required: true, message: '请输入循环次数', trigger: 'blur' }
    ],
    timeLimit: [
      { required: true, message: '请输入考试时长', trigger: 'blur' }
    ],
    examType: [
      { required: needExamType, message: '请选择考试类型', trigger: 'change' }
    ]
  })

  watch(() => props.config, (formData) => {
    for(const key in formData) {
      ruleForm[key] = formData[key]
    }
  })
  
  // 预览
  const previewPaper = (row: papaerDataType) => {
    data.selectPaperRow = row;
    data.previewDialog = true;
  }

  // 获取已经选择的试卷
  const getSelectPaperInfo = async (id: string) => {
    const { code, data: { list } } = await $axios.post('/training.exam.api/paper/list', {
      branchId,
      brandId,
      pageNo: 1,
      pageSize: 10,
      paperIds: [id],
      rowCntPerPage: 10
    });

    if (code === '200') {
      data.paperList = list;
    }
  }

  // 如果 paperId 存在则获取试卷数据
  const paperId = route.query.paperId as string;
  if (paperId) {
    ruleForm.paperId = paperId;
    getSelectPaperInfo(paperId);
  }

  // 显示选择试卷弹窗
  const showSelectDialog = () => {
    data.selectDialog = true;
  }
  const closeSelectDialog = () => {
    data.selectDialog = false;
  }

  // 关闭预览弹窗
  const closePreviewDialog = () => {
    data.previewDialog = false;
  }

  // 更新选择题库
  const updateSelectData = (data: papaerDataType) => {
    ruleForm.paperId = data.paperId;
    getSelectPaperInfo(data.paperId)
  }

  // 获取考试类型
  const getExamType = () => {
    $axios.post('/training.exam.api/types/list', {
      isEnabled: 1,
      pageSize: 999,
      pageNo: 1
    })
    .then((res: ResponseType) => {
      if (res.succeed) {
        data.typesList = res.data.list || []
      }
    })
  }

  // 更新考试类型
  const examTypeChange = (typeId: string) => {
    const selectData =  data.typesList.filter(item => item['typeId'] === typeId)[0];
    for (const key in props.config) {
      if (key !== 'timeLimit' && selectData[key]) { // 不重置考试时间
        ruleForm[key] = selectData[key]
      }
    }
  }

  const ruleFormRef = ref<InstanceType<typeof ElForm>>()
  const submitConfig = () => {
    if (!ruleForm.paperId) {
      $message.error('请先选择试卷');
      return;
    }
    ruleFormRef.value?.validate((valid) => {
      if (valid) {
        emit('update:config', { ...ruleForm });
        emit('verify');
      } else {
        return false
      }
    })
  }

  const goBack = () => {
    const { fullPath, examTags } = getPrevRouteInfo(route.fullPath);
    router.push(fullPath)
    store.commit('setCurrentTags', examTags)
  }
  
  onMounted(() => {
    getExamType();
  })

  defineExpose({ configFormData: ruleForm })
</script>

<template>
  <div>
    <div class="header">
      <span class="title">试卷</span>
      <el-button type="primary" @click="showSelectDialog"><el-icon><plus /></el-icon>选择试卷</el-button>
    </div>
    <el-table 
      :data="data.paperList" 
      :border="true"
      style="width: 100%">
      <el-table-column prop="paperCode" label="ID" />
      <el-table-column prop="title" label="试卷" />
      <el-table-column prop="totalGrade" label="总分" />
      <el-table-column prop="passGrade" label="及格分" />
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button @click="previewPaper(row)">预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 选择试卷弹窗 -->
    <SelectPaper v-model:selectDailog="data.selectDialog" @close="closeSelectDialog" @updateSelectData="updateSelectData"/>

     <!-- 试卷预览 -->
    <PaperPreview v-model:previewDialog="data.previewDialog" :paperData="data.selectPaperRow" @close="closePreviewDialog"/>
    
    <div class="title">考试规则</div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="140px"
    >
      <el-form-item label="考试时长：" prop="timeLimit">
        <el-input v-model="ruleForm.timeLimit" style="width:205px">
          <template #append>分钟</template>
        </el-input>
      </el-form-item>
      <el-form-item label="考试类型：" prop="examType">
        <el-select v-model="ruleForm.examType" placeholder="请选择相关考试类型" @change="examTypeChange">
          <el-option
            v-for="type in data.typesList"
            :label="type['title']"
            :value="type['typeId']"
            :key="type['typeId']"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考试循环方式：" class="remove-flex">
        <el-radio
          disabled
          v-for="type in data.cycleType"
          :key="type.key"
          v-model="ruleForm.cycleType"
          :label="type.key"
        >
          {{ type.val }}
        </el-radio>
        <div class="tip-required">
          考试循环方式，将影响同一考试在指定期限内的需参加考试次数： <br>

          仅一次：期限内参加一次即可；<br>

          每日一次：于每日早7点派发试卷，需于当日23点前参加考试；<br>

          每周一次：于每周一早7点派发试卷，需于同周周日23点前参加考试；<br>

          每月一次：于每月1号早7点派发试卷，需于同月最后一天23点前参加考试； <br>
        </div>

        <div class="tip-required">
          多次轮循的考试，若上一次未通过，需先处理上次考试，再进行同考试的下次轮循考试；同时若轮循中有任一次未通过，即视为考试不通过。<br>

          （例如，公司设置考试开始时间1月1日，考试结束时间1月7日，循环方式为每日一次；参考人员A，于1日未通过考试，需在1日重考至通过，若2日依然未通过，需补考通过，才可以参加1月2日的考试。以此类推。若于7日依然有该轮训内的考试未通过，则考试不及格，系统将被禁用，补考或联系管理员处理）
        </div>
      </el-form-item>
      <el-form-item label="考试开始日期：" prop="startTm">
        <el-date-picker
          v-model="ruleForm.startTm"
          :type="ruleForm.cycleType !== 4 ? 'date' : 'month'"
          placeholder="请选择开始日期"
          value-format="x"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="考试结束日期：" prop="endTm" v-if="ruleForm.cycleType == 1">
        <el-date-picker
          v-model="ruleForm.endTm"
          type="date"
          value-format="x"
          placeholder="请选择开始日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="考试循环次数：" prop="cycleTimes" ref="formCycleTimes" v-else>
        <el-input
          disabled
          style="width:220px"
          v-model.number="ruleForm.cycleTimes"
          placeholder="请输入循环次数"
        >
          <template #append>{{ unit }}</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitConfig">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .title {
    font-size: 14px;
    margin: 10px 0 10px;
    font-weight: 700;
  }
  .tip-required {
    font-size: 12px;
    color: #999;
    line-height: 20px;
  }

  :deep(.el-input__suffix .el-icon.el-input__icon.el-input__validateIcon) {
    display: none;
  }
  :deep(.remove-flex .el-form-item__content) {
    display: block;
  }
</style>